"use script"; //开发环境建议开启严格模式

var map;
var basemapId;
var basemapLayer;
var currentMode; //当前页面显示的系数种类
var graphicLayer; //噪声点位POI图层
var fzLayer; //辅助点位图层
var tsLayer; //投诉点位图层
var yqdLayer; //源清单点位图层
var heatCircleLayer; //噪声扩散图层
var viewShedLayer; //噪声来源图层
var currentCenter; //当前中心点坐标
var currentCamerView; //当前屏幕视角

function initMap(options) {
  //合并属性参数，可覆盖config.json中的对应配置
  var mapOptions = mars3d.Util.merge(options, {
    scene: {
      requestRenderMode: true,
      center: {
        lat: 22.191771,
        lng: 113.506111,
        alt: 12839,
        heading: 8,
        pitch: -72,
      },
    },
  });

  //创建三维地球场景
  map = new mars3d.Map("mars3dContainer", mapOptions);
  map.basemap = 1010; //北大底图去除边界
  basemapId = 1010;

  // map.scene.light = new Cesium.DirectionalLight({
  //   direction: map.scene.camera.direction,
  // });

  // map.on(mars3d.EventType.cameraMoveEnd, function (event) {
  //   map.scene.light.direction = map.scene.camera.direction;
  // });

  // var bloomEffect = new mars3d.effect.BloomEffect({
  //   enabled: false,
  //   brightness: -0.4,
  // });
  // map.addEffect(bloomEffect);

  loadDefaultModel(); // 加载白模
  loadB3dmLayer(); //加载倾斜模型

  // 初始化poi点图层并添加
  graphicLayer = new mars3d.layer.GraphicLayer();
  map.addLayer(graphicLayer);
  // 初始化辅助点位图层并添加
  fzLayer = new mars3d.layer.GraphicLayer();
  map.addLayer(fzLayer);
  // 初始化投诉点位图层并添加
  tsLayer = new mars3d.layer.GraphicLayer();
  map.addLayer(tsLayer);
  // 初始化源清单点位图层并添加
  yqdLayer = new mars3d.layer.GraphicLayer();
  map.addLayer(yqdLayer);
  // 初始化噪声来源图层并添加
  viewShedLayer = new mars3d.layer.GraphicLayer();
  map.addLayer(viewShedLayer);
  // 初始化噪声扩散图层
  heatCircleLayer = new mars3d.layer.GraphicLayer();
  map.addLayer(heatCircleLayer);
  //webgl渲染失败后，刷新页面
  map.on(mars3d.EventType.renderError, function (event) {
    console.log("err", event);
    // debugger;
    window.location.reload(true);
    alert("请手动点击浏览器刷新按钮刷新页面！");
  });
}

//23D切换
function viewModeChange2() {
  // 获取当前屏幕四个角点经纬度
  var currentExtent = map.getExtent();
  // console.table(currentExtent);
  // 获取当前中心点位置参数
  currentCenter = map.getCenter();
  // console.log("before: " + currentCenter);
  // 获取当前视角参数
  currentCamerView = map.getCameraView();
  // 获取当前视角高度
  var currentCamerViewHeight = currentCamerView.alt;
  // 确定要转换的视角经纬度及高度
  var currentView = new mars3d.LngLatPoint(
    currentCenter._lng,
    currentCenter._lat,
    currentCamerViewHeight
  );

  if (currentCamerView.pitch <= -85) {
    // 切换为3D视角
    map.flyToExtent(
      {
        xmin: currentExtent.xmin,
        xmax: currentExtent.xmax,
        ymin: currentExtent.ymin,
        ymax: currentExtent.ymax,
        // height: 400
      },
      {
        pitch: -45,
      }
    );
    currentCenter = map.getCenter();
  } else {
    // 切换2D视角
    map.flyToPoint(currentView, {
      pitch: -90,
    });
    currentExtent = map.getExtent();
  }
}

function fly2fbx(pos) {
  map.flyToPoint(new mars3d.LngLatPoint(pos[0], pos[1], 0), {
    pitch: -90,
  });
}

function changeBaseMap() {
  if (basemapId == 1001) {
    map.basemap = 1010;
    basemapId = 1010;
  } else {
    map.basemap = 1001;
    basemapId = 1001;
  }
}

// 返回初始视图
function goHome() {
  map.flyToExtent(
    {
      xmin: 113.43420455765437,
      xmax: 113.58021591803984,
      ymin: 22.19691687544376,
      ymax: 22.303532602408037,
    },
    {
      pitch: -59,
      heading: 0,
    }
  );
}

// 环绕旋转
var isRollFlag = false;
var rollPoint = null;
function rollPos(_speed) {
  if (!isRollFlag) {
    rollPoint = new mars3d.thing.RotatePoint({
      direction: false,
      time: _speed == undefined ? 120 : _speed,
    });
    map.addThing(rollPoint);
    currentCenter = map.getCenter();
    rollPoint.start(currentCenter);
    isRollFlag = true;
  } else {
    rollPoint.stop();
    isRollFlag = false;
  }
}

// 视角保存
var defaultViewPos;
function setDefaultViewPos() {
  defaultViewPos = map.getCameraView();
  if (currentSinglePos != null) {
    if (getDistance(currentSinglePos, defaultViewPos) > 300) {
      toastr.error("当前位置与监测点位偏移超过300米，设置失败。");
      defaultViewPos = null;
    } else {
      $.ajax({
        type: "POST",
        url: apiUrl + "comleader/dataOutput/saveGisCameraParam",
        dataType: "application/json",
        headers: {
          "Content-Type": "application/json",
          accessToken: "comleader@123",
        },
        data: JSON.stringify({
          pointCode: currentSinglePos.pointCode,
          angle: map.getCameraView(),
        }),
        complete: (res) => {
          if (res.readyState == 4) {
            toastr.success("视角信息保存成功!");
          } else {
            toastr.error("保存视角接口错误,请稍后重试！");
          }
        },
        failed: (res) => {
          toastr.error(res);
        },
      });
      defaultViewPos = map.getCameraView();
    }
  } else {
    toastr.info("请先选择要保存默认视角的点位。");
  }
}

// 返回空间两点间距离
function getDistance(pos1, pos2) {
  var tempDistance = mars3d.MeasureUtil.getDistance(
    [
      new mars3d.LngLatPoint(
        pos1.longitude == undefined ? pos1.longtitude : pos1.longitude,
        pos1.latitude,
        0
      ),
      new mars3d.LngLatPoint(pos2.lng, pos2.lat, 0),
    ],
    false
  );
  console.log("当前距离点位距离:", tempDistance);
  return tempDistance;
}

// 视角复位
function flyToDefaultViewPos() {
  if (currentSinglePos == null) {
    toastr.info("请先选择要飞行的点位！");
  } else {
    $.ajax({
      type: "POST",
      url: apiUrl + "comleader/dataOutput/getGisCameraParam",
      dataType: "application/json",
      headers: {
        "Content-Type": "application/json",
        accessToken: "comleader@123",
      },
      data: JSON.stringify({
        pointCode: currentSinglePos.pointCode,
      }),
      complete: (res) => {
        if (res.readyState == 4) {
          if (JSON.parse(res.responseText).data.angle != "") {
            // 后台返回视角坐标格式有误，将=转为：再生成视角object
            var resDataAngle = JSON.parse(res.responseText).data.angle.replace(
              /=/g,
              ":"
            );
            var defaultViewPos = eval("(" + resDataAngle + ")");
            console.log(defaultViewPos);
            map.setCameraView(defaultViewPos);
          } else {
            toastr.info(currentSinglePos.pointCode + "暂未设置默认视角！");
          }
        } else {
          toastr.error("获取视角接口错误,请稍后重试！");
        }
      },
      failed: (res) => {
        toastr.error(res);
      },
    });
  }
}

// 清除所有点位图层
function removeAllPosLayer() {
  //绝大多数噪声点位POI图层
  if (graphicLayer != null) {
    clearInterval(reVoiceDataInter);
    map.removeLayer(graphicLayer);
    graphicLayer = null;
    graphicLayer = new mars3d.layer.GraphicLayer();
    map.addLayer(graphicLayer);
  }
  //辅助点位图层
  if (fzLayer != null) {
    map.removeLayer(fzLayer);
    fzLayer = null;
    fzLayer = new mars3d.layer.GraphicLayer();
    map.addLayer(fzLayer);
  }
  //投诉点位图层
  if (tsLayer != null) {
    map.removeLayer(tsLayer);
    tsLayer = null;
    tsLayer = new mars3d.layer.GraphicLayer();
    map.addLayer(tsLayer);
  }
  //源清单点位图层
  if (yqdLayer != null) {
    map.removeLayer(yqdLayer);
    yqdLayer = null;
    yqdLayer = new mars3d.layer.GraphicLayer();
    map.addLayer(yqdLayer);
  }
  //热力图图层
  if (heatLayer != null) {
    clearInterval(drawHeatDataInter);
    map.removeLayer(heatLayer);
  }
}

// 图层显隐控制
function showBar() {
  document.querySelector(".right-bar").style.display = "block";
}
function hideBar() {
  document.querySelector(".right-bar").style.display = "none";
}
